// 封装axios
import axios from "axios";
import store from '../store/index.js'
import {ElMessage} from 'element-plus'
import router from "../router/index.js";

const request = axios.create({
  baseURL: "http://localhost:8090",
  timeout: 3000
})

request.interceptors.request.use(config => {
  const token = store.state.token;
  if (token) {
    config.headers.token = token;
  }
  return config;
}, error => {
  return Promise.reject(error);
})

request.interceptors.response.use(resp => {
  const {data} = resp; // 从响应的数据中获取自己封装data
  const token = resp.headers.token;
  if (data.code === 2000) {
    if (token) {
      store.commit("SET_TOKEN", token);
    }
    return data;
  } else if (data.code === 6000) {
    ElMessage.error("登录失败")
    return Promise.reject(data.message);
  } else if (data.code === 7000) {
    ElMessage.error("TOKEN异常")
    router.push({name: "login"})
  } else {
    return Promise.reject(data.message);
  }
}, error => {
  // 发生异常的时候, http的异常
  return Promise.reject(error);
})

export default request
